let http = require('http');
let os = require('os');
let Util = require('./lib/Util');
let {PORT, DEBUG} = Util.getRunParams();
//console.log('run:params', {PORT, DEBUG, START});
if ('linux' !== os.platform()) throw '当前只能适用于linux系统';
let Monitor = require('./lib/Monitor');
let monitor = new Monitor({debug: DEBUG});

let INTERVAL_TIME = 30000;
let __monitorData = {};

getMonitor(1);
setInterval(() => {
    getMonitor();
}, INTERVAL_TIME);

http.createServer(function (request, response) {
    if(request.url === '/monitor') {
        response.writeHead(200,{
            "Content-Type":'application/json',
            'charset':'utf-8',
            'Access-Control-Allow-Origin':'*',
            'Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'
        });
        response.write(JSON.stringify(__monitorData));
        response.end();
    }
}).listen(PORT);

function getMonitor(netTime) {
    monitor.GetMonitorData(netTime)
        .then(data => {
            __monitorData = data;
        })
        .catch(error => {
            __monitorData = {};
            console.error('Interval:error:', error)
        })
}

function getIPAddress(select) {
    var interfaces = os.networkInterfaces();
    var map = {};
    for (var attr in interfaces) {
        var iface = interfaces[attr];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family !== 'IPv4') continue;
            let a = alias.address.split('.')[0];
            if (a !== '127' && a !== '192' && a !== '10' && a !== '172') a = 0;
            map[a] = alias.address;
        }
    }
    if (!!select) return map[select] || '';
    if(! map[0]) map[0] = map[192];
    if(! map[0]) map[0] = 'hostname';
    return map[0] || '';
}

console.log('monitor running at port: http://' + getIPAddress() + ':' + PORT + '/monitor');
